/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/construct-binary-tree-from-preorder-and-inorder-traversal
   @Language: C++
   @Datetime: 16-02-09 05:45
   */

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
	/**
	 *@param preorder : A list of integers that preorder traversal of a tree
	 *@param inorder : A list of integers that inorder traversal of a tree
	 *@return : Root of a tree
	 */
	TreeNode *buildTree(vector<int> &inorder, vector<int> &preorder
			,int begin,int end,int &pos){
		if (pos>=preorder.size() || begin>=end) return NULL;
		TreeNode *root = new TreeNode(preorder[pos]);
		int cur = begin;
		for(; cur<end && inorder[cur]!=preorder[pos];++cur);
		++pos;
		root->left = buildTree(inorder,preorder,begin,cur,pos);
		root->right = buildTree(inorder,preorder,cur+1,end,pos);
		return root;
	}

public:
	TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
		// write your code here
		int pos = 0;
		return buildTree(inorder,preorder,0,inorder.size(),pos);
	}
};
